package uk.co.douglashoskins.weathercompare.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;

import uk.co.douglashoskins.weathercompare.providers.BBC;
import uk.co.douglashoskins.weathercompare.providers.BBCEntry;
import uk.co.douglashoskins.weathercompare.services.LocationService;

public class LocationController {
	public static final double DEF_LAT = 50.833d;
	public static final double DEF_LNG = -0.3d;
	public static final String DEF_LOC = "Brighton";
	private LocationService ls;
	public LocationToDisplay getLastLocation() {
		try {
			RecordStore rms = RecordStore.openRecordStore("loc", true);
			if (rms.getNumRecords() == 1) {
				byte[] bytes = rms.getRecord(1);
				rms.closeRecordStore();
				ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
				DataInputStream dis = new DataInputStream(bais);
				return new LocationToDisplay(dis.readDouble(), dis.readDouble(), dis.readUTF());
			}
		} catch (RecordStoreFullException e) {
			e.printStackTrace();
		} catch (RecordStoreNotFoundException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new LocationToDisplay(DEF_LAT, DEF_LNG, DEF_LOC);
	}

	public void findLocation(final BBC bbc, final Callback c) {
		try {
			if (ls == null) {
				ls = new LocationService();
			}
			new Thread(new Runnable() {
				
				public void run() {
					double[] pos = ls.getPos();
					if (pos != null) {
						try {
							ByteArrayOutputStream baos = new ByteArrayOutputStream();
							DataOutputStream dos = new DataOutputStream(baos);
							BBCEntry entry = bbc.closest(pos[0], pos[1]);
							dos.writeDouble(entry.lat);
							dos.writeDouble(entry.lng);
							dos.writeUTF(entry.location);
							byte[] bytes = baos.toByteArray();
							RecordStore rms = RecordStore.openRecordStore("loc", true);
							if (rms.getNumRecords() == 1) {
								rms.setRecord(1, bytes, 0, bytes.length);
							} else {
								rms.addRecord(bytes, 0, bytes.length);
							}
							LocationToDisplay ltd = new LocationToDisplay(entry.lat, entry.lng, entry.location);
							c.callback(ltd);
							rms.closeRecordStore();
						} catch (RecordStoreFullException e) {
							e.printStackTrace();
						} catch (RecordStoreNotFoundException e) {
							e.printStackTrace();
						} catch (RecordStoreException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}).start();
		} catch (Exception e) {
			c.callback(null);
		}
	}
}
